<template>
  <div>
    <div class="operation-group">
      <el-button plain type="single-number" @click="chooseInventory">
        选择库存
      </el-button>
      <el-button plain type="single-number" @click="chooseContract">
        删除行
      </el-button>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <ux-grid
        ref="plxTable"
        keep-source
        widthResize
        show-overflow="title"
        show-summary
        :summary-method="getSummaries"
        @select-all="handleCheckChange"
        @select="handleCheckChange"
        :header-cell-class-name="must"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        :data="tableData"
      >
        <ux-table-column
          type="checkbox"
          width="55"
          fixed="left"
          show-overflow="none"
        />
        <ux-table-column title="序号" type="index" width="50" fixed="left" />

        <ux-table-column
          :show-overflow-tooltip="true"
          field="batchNumber"
          title="批次号"
          width="200"
          fixed="left"
        >
          <template v-slot="scope">
            <span>{{ scope.row.batchNumber }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="materialCode"
          title="设备物资编码"
          width="150"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.materialCode }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="materialName"
          title="设备物资名称"
          width="300"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.materialName }}</span>
          </template>
        </ux-table-column>

        <ux-table-column 
          :show-overflow-tooltip="true"
          field="materialState"
          title="设备物资说明"
          width="130"
          :edit-render="{ autofocus: '.el-input__inner' }"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <el-input
              v-model="scope.row.materialState"
              placeholder="请输入设备物资说明"
              clearable
              type="text"
            >
            </el-input>
          </template>
          <template v-slot="scope">
            <span
              class="my-input-sc"
              >{{ scope.row.materialState }}</span
            >
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="categoryName"
          title="分类名称"
          width="130"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.categoryName }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="measureUnit"
          title="计量单位"
          width="90"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.measureUnit }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="storageCount"
          title="库存数量"
          width="120"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.storageCount }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="unStockCount"
          title="可用库存数量"
          width="120"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.unStockCount }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="exwarehouseCount"
          title="出库数量"
          width="150"
          :edit-render="{ autofocus: '.el-input__inner' }"
          :resizable="true"
        >
          <template v-slot:edit="scope">
            <el-input
              v-model="scope.row.exwarehouseCount"
              placeholder="请输入出库数量"
              maxlength="12"
              :max="scope.row.unStockCount"
              @blur="handleNumber(scope.row)"
              @keyup.native="scope.row.exwarehouseCount = oninput(scope.row)"
              v-if="scope.row.isOtherCost == 0 && scope.row.isServices == 0"
            >
            </el-input>
          </template>
          <template v-slot="scope">
            <span
              class="my-input-sc"
              v-if="scope.row.isOtherCost == 0 && scope.row.isServices == 0"
              >{{ scope.row.exwarehouseCount }}</span
            >
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="currencyName"
          title="币种"
          width="90"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.currencyName }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="exchangeRate"
          title="汇率"
          width="90"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.exchangeRate }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="unitPriceWithTax"
          title="含税单价"
          width="140"
          align="right"
          header-align="left"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.unitPriceWithTax | filterTax }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          :show-overflow-tooltip="true"
          field="exwarehouseMoney"
          title="出库金额"
          width="140"
          align="right"
          header-align="left"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.exwarehouseMoney | filterTax }}</span>
          </template>
        </ux-table-column>
        <!-- <ux-table-column
          :show-overflow-tooltip="true"
          field="storageTypeName"
          title="入库类型"
          width="100"
        >
          <template v-slot:edit="scope">
            <span>{{ scope.row.storageTypeName}}</span>
          </template>
        </ux-table-column> -->

        <ux-table-column
          :show-overflow-tooltip="true"
          field="remark"
          title="备注"
          width="140"
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="请输入备注"
              clearable
              type="text" 
              maxlength="500"
            >
            </el-input>
          </template>
          <template v-slot="scope">
            <span class="my-input-sc">{{ scope.row.remark }}</span>
          </template>
        </ux-table-column>
      </ux-grid>
    </div>
    <dialogMultiSelectTableTow
      ref="inventory"
      @confirm="confirm"
      :warehouseId="warehouseIdId"
    ></dialogMultiSelectTableTow>
  </div>
</template>

<script>
import dialogMultiSelectTableTow from "../components/dialogMultiSelectTableTow";
import BigNumber from "bignumber.js";
export default {
  name: "contractList",
  data() {
    return {
      tableData: [],
      tempArr: [], //选择的
      tableDataClone: [], //复制列表
      warehouseIdId: "" //仓库id
    };
  },
  props: {
    warehouseId: {
      type: String,
      default() {
        return "";
      }
    },
    purchaseList: {
      type: Array,
      default() {
        return [];
      }
    }
  },

  components: {
    dialogMultiSelectTableTow
  },
  created() {},
  watch: {
    tableData(data) {
      if (data.length > 0) {
        let categoryName = data[0].categoryName;
        let categoryCode = data[0].categoryCode;
        this.$emit("categoryName", categoryName);
        this.$emit("categoryCode", categoryCode);
      } else {
        this.$emit("categoryName", "");
        this.$emit("categoryCode", "");
        this.$emit("exwarehouseCountSum", "");
        this.$emit("exwarehouseMoneySum", "");
      }
      this.$nextTick(() => {
        //表格铺数据
        this.$refs.plxTable.reloadData(data);
      });
    },
    warehouseId(data) {
      this.warehouseIdId = data;
    },
    purchaseList(data) {
      this.tableData = data;
      if (this.$route.query.ifAdd == 2) {
        this.tableDataClone = JSON.parse(JSON.stringify(this.tableData));
      }
    }
  },
  filters: {
    filterTax(value) {
      return Number(value).toFixed(2);
    }
  },
  methods: {
    handleNumber(row) {
      if (row.exwarehouseCount) {
        let num = Number(row.exwarehouseCount).toFixed(3);
        this.$set(row, "exwarehouseCount", num);

        // if (Number(row.exwarehouseCount) === 0) {
        //   this.$set(row, "exwarehouseCount");
        //   this.$set(row, "exwarehouseMoney");
        //   this.$set(row, "moneyWithoutTax");
        //   this.$message({
        //     message: "出库数量应大于0",
        //     type: "error",
        //     showClose: true,
        //     ccuiCustom: true
        //   });
        // } else {
        //   let num = Number(row.exwarehouseCount).toFixed(3);
        //   this.$set(row, "exwarehouseCount", num);
        // }
        //前端不做校验了
        // if (Number(row.unStockCount) < Number(row.exwarehouseCount)) {
        //   this.$set(row, "exwarehouseCount");
        //   this.$set(row, "exwarehouseMoney");
        //   this.$set(row, "moneyWithoutTax");
        //   this.$message({
        //     message: "出库数量应小于等于可用库存数量",
        //     type: "error",
        //     showClose: true,
        //     ccuiCustom: true
        //   });
        // }
        if (row.exwarehouseCount) {
          //出库金额 == 含税单价x出库数量
          let exwarehouseMoney = new BigNumber(Number(row.unitPriceWithTax))
            .multipliedBy(row.exwarehouseCount)
            .toNumber();
          let exwarehouseMoneyNum = Number(exwarehouseMoney).toFixed(2);
          this.$set(row, "exwarehouseMoney", exwarehouseMoneyNum);

          //不含税金额
          let moneyWithoutTax = new BigNumber(Number(row.unitPriceWithoutTax))
            .multipliedBy(row.exwarehouseCount)
            .toNumber();
          let moneyWithoutTaxNum = Number(moneyWithoutTax).toFixed(2);
          this.$set(row, "moneyWithoutTax", moneyWithoutTaxNum);
        }
      } else {
        this.$set(row, "exwarehouseMoney");
        this.$set(row, "moneyWithoutTax");
      }
    },
    oninput(row) {
      //正则替换
      //后来调试发现这个函数只能用于字符串，当是数字的时候就会报此错误
      var str = row.exwarehouseCount.toString();
      str = str.replace(/[^\d.]/g, ""); // 保留数字   /[^\d.]/g, ""
      str = str.replace(/^\./g, ""); // 必须保证第一个为数字而不是.
      str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      // 限制几位小数
      const arr = str.split(".");
      if (arr[arr.length - 1].length > 3 && arr.length == 2) {
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 1 && str.length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = str.substr(0, str.length - 1);
      } else if (arr.length == 2 && arr[0].length > 12) {
        this.$message.warning("整数最多可以输入12位");
        str = arr[0].substr(0, arr[0].length - 1);
      }
      return str;
    },
    //插件数据
    confirm(data) {
      let newArr = [];
      if (this.tableData.length > 0) {
        this.tableData.forEach(item => {
          if (item.batchNumber) {
            newArr.push(item.batchNumber);
          }
        });
      }
      data.forEach((item, index) => {
        //弹框数据
        item.storageTypeName = item.storageType === 0 ? "暂估" : "正式";
        if (item.availableStockCount || item.availableStockCount === 0) {
          item.unStockCount = Number(item.availableStockCount).toFixed(3);
        }
        if (item.actualStockCount || item.actualStockCount === 0) {
          item.storageCount = Number(item.actualStockCount).toFixed(3);
        }
        if (item.isOtherCost == 1 || item.isServices == 1) {
          item.exwarehouseMoney = item.actualStockWithTax;
        }
        if (this.tableData.length > 0) {
          let storageType;
          if (
            this.tableData[0].storageType ||
            this.tableData[0].storageType === 0
          ) {
            storageType = this.tableData[0].storageType;
          } else {
            storageType = this.tableData[0].exwarehouseType;
          }
          if (storageType == item.storageType) {
            //判断是否相同入库类型
            if (item.unStockCount || item.unStockCount === 0) {
              item.unStockCount = Number(item.unStockCount).toFixed(3);
              this.$set(item, "exwarehouseCount", item.unStockCount);
              if (item.unitPriceWithTax) {
                //加载后计算出库金额
                let exwarehouseMoney = new BigNumber(
                  Number(item.unitPriceWithTax)
                )
                  .multipliedBy(item.exwarehouseCount)
                  .toNumber();
                let exwarehouseMoneyNum = Number(exwarehouseMoney).toFixed(2);
                this.$set(item, "exwarehouseMoney", exwarehouseMoneyNum);
              }
            }
            this.$set(item, "remark", "");
            if (!newArr.includes(item.batchNumber)) {
              this.tableData.push(item);
            }
          } else {
            if (index === data.length - 1) {
              this.$message.warning("请选择相同入库类型的物资进行出库！");
            }
          }
        } else {
          if (item.unStockCount || item.unStockCount === 0) {
            item.unStockCount = Number(item.unStockCount).toFixed(3);
            this.$set(item, "exwarehouseCount", item.unStockCount);
            if (item.unitPriceWithTax) {
              //加载后计算出库金额
              let exwarehouseMoney = new BigNumber(
                Number(item.unitPriceWithTax)
              )
                .multipliedBy(item.exwarehouseCount)
                .toNumber();
              let exwarehouseMoneyNum = Number(exwarehouseMoney).toFixed(2);
              this.$set(item, "exwarehouseMoney", exwarehouseMoneyNum);
            }
          }
          this.$set(item, "remark", "");
          if (!newArr.includes(item.batchNumber)) {
            //去重
            this.tableData.push(item);
          }
        }
      });
    },
    must(obj) {
      //给表头加必选标识
      if (obj.column.title == "出库数量") {
        return "must";
      }
    },
    //选择库存
    chooseInventory() {
      if (this.warehouseIdId === "") {
        this.$message.warning("请先选择仓库");
      } else {
        this.$refs.inventory.showDialogVisible = true;
        this.$refs.inventory.ifTrue = true;
        this.$refs.inventory.getTableList(this.$refs.inventory.formData);
      }
    },
    // 删除行
    chooseContract() {
      if (this.tempArr.length < 1) {
        this.$message.warning("请选择一项");
        return;
      }
      let newArr = [];
      this.tableData.forEach(item => {
        if (!this.tempArr.includes(item.batchNumber)) {
          newArr.push(item);
        }
      });
      this.tableData = newArr;
      // this.$emit("delectList", filterArr);
    },
    formSearchHandler() {},
    formSearchChange() {},
    // 列表单选 多选
    handleCheckAllChange(val) {
      if (val.length > 0) {
        val.forEach(item => {
          item.check = true;
        });
      }
    },
    handleCheckChange(val) {
      this.tempArr = val.map(item => item.batchNumber);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums.push("合计");
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if (
                column.title == "库存数量" ||
                column.title == "可用库存数量" ||
                column.title == "出库数量" ||
                column.title == "出库金额"
              ) {
                return prev + curr;
              }
            } else {
              return prev;
            }
          }, 0);
          if (column.title == "库存数量") {
            sums[index] = sums[index] ? sums[index].toFixed(3) : "";
          }
          if (column.title == "可用库存数量") {
            sums[index] = sums[index] ? sums[index].toFixed(3) : "";
          }
          if (column.title == "出库数量") {
            sums[index] = sums[index] ? sums[index].toFixed(3) : "";
          }
          if (column.title == "出库金额") {
            sums[index] = sums[index].toFixed(2);
          }
        } else {
          sums[index] = "";
        }
        if (sums[10]) {
          let exwarehouseCountSum = (+sums[10]).toFixed(3); //出库数量合计
          this.$emit("exwarehouseCountSum", exwarehouseCountSum);
        }
        if (sums[14]) {
          let exwarehouseMoneySum = (+sums[14]).toFixed(2); //出库金额合计
          this.$emit("exwarehouseMoneySum", exwarehouseMoneySum);
        }
      });
      return [sums];
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table th.must > .cell:before {
  content: "*";
  color: #ff1818;
  margin-right: 5px;
}

.relationBox {
  display: flex;
  justify-content: center;
  align-items: center;
}

.relationBox .relationRight {
  display: inline-block;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 5px;
}

.operation-group {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
}

/deep/ .ccui-form .ccui-form-child-table.el-table .el-input .el-input__inner {
  border: 1px solid #ccc;
}

/deep/ .ccui-multifunctional-table-wrapper {
  .el-table td,
  .el-table th.is-leaf {
    border-right: 1px solid #edf2fc;
  }

  .ccui-table-footer {
    padding-top: 0 !important;
  }
}

/deep/ .el-table__footer-wrapper {
  margin-top: 0px;
}

/deep/ .el-button.el-button--primary-font-mini {
  padding: 0 15px !important;
}

// 解决表格定位滚动条无法拖动
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}

/deep/ .el-table__fixed,
/deep/ .el-table__fixed-right {
  pointer-events: none;

  td {
    pointer-events: auto;
  }
}

/deep/ .elx-table.is--empty .elx-table--empty-placeholder {
  top: 40px !important;
  height: 40px !important;
}

/deep/ .elx-table .elx-body--column.col--ellipsis,
.elx-table.elx-editable .elx-body--column {
  font-size: 13px;
}

.my-input-sc {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  -webkit-appearance: none;
  background-color: #ffffff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  font-size: inherit;
  outline: none;
  padding: 0 8px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
</style>
